package com.ruoyi.smart.service.impl;

import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.GraphUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.smart.domain.*;
import com.ruoyi.smart.service.*;
import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.smart.mapper.SmartProcessDataMapper;

/**
 * 工序数据Service业务层处理
 * 
 * @author minwei
 * @date 2022-05-17
 */
@Service
public class SmartProcessDataServiceImpl implements ISmartProcessDataService 
{
    @Autowired
    private SmartProcessDataMapper smartProcessDataMapper;
    @Autowired
    private ISmartProductService smartProductService;
    @Autowired
    private ISmartModDataService smartModDataService;
    @Autowired
    private ISmartProductModelService smartProductModelService;
    @Autowired
    private ISmartPlanTaskService smartPlanTaskService;
    @Autowired
    private ISmartProductTestService smartProductTestService;
    @Autowired
    private SmartProductTestWaveformServiceImpl smartProductTestWaveformService;
    /**
     * 查询工序数据
     * 
     * @param id 工序数据主键
     * @return 工序数据
     */
    @Override
    public SmartProcessData selectSmartProcessDataById(Long id)
    {
        return smartProcessDataMapper.selectSmartProcessDataById(id);
    }


    @Override
    public void insertString(String str)
    {
        //str="2020-09-11 12:41:28.305?Dev_GetInfo?1?Id=20070101?Ver=0x2B";
        BeanListProcessor<SmartProcessData> rowProcessor = new BeanListProcessor<SmartProcessData>(SmartProcessData.class);
        // 创建csv解析器settings配置对象
        CsvParserSettings settings = new CsvParserSettings();
        settings.setDelimiterDetectionEnabled(true, '&');
        // 也可以正确处理（MacOS使用'\r'；Windows使用'\r\n'）
        settings.getFormat().setLineSeparator("\r\n");
        settings.setProcessor(rowProcessor);
        // 创建CSV解析器（将分隔符传入对象）
        CsvParser parser = new CsvParser(settings);
        // 调用beginParsing逐个读取记录，使用迭代器iterator
        parser.parse(new ByteArrayInputStream(str.getBytes()));
        List<SmartProcessData> beans = rowProcessor.getBeans();
        System.out.println(beans.size());
        System.out.println(JSON.toJSON(beans).toString());

        parser.stopParsing();
        for (SmartProcessData smartProcessData:beans)
        {
            diversionData(smartProcessData);
            smartProcessData.setState(0l);
            smartProcessData.setCreateTime(new Date());
            smartProcessDataMapper.insertSmartProcessData(smartProcessData);
        }
    }

    //这个方法用于将数据分流，
    // 把工序数据存入不同的地方
    // 需要插入其他表的数据从开头进行依赖注入
    private void diversionData(SmartProcessData smartProcessData){
        //获取全部简单图
        GraphUtils.getJohnsonSimpleCycles();
       System.out.println(new Date().toLocaleString() +"调用数据分流任务");
    }

    //这个方法用于给定时器调用，
    // 用来处理处理数据分流
    public void IntervalDiversionData(){
        System.out.println(new Date().toLocaleString() +"调用定时数据分流任务");
        //查询出所有的数据
        /*SmartProcessData smartProcessData=new SmartProcessData();
        smartProcessData.setValueSearch("Id=");
        smartProcessData.setState(0l);
        List<SmartProcessData> list=selectSmartProcessDataList(smartProcessData);*/
        // 插入产品的波形
        insertProductTestWaveform();
        //插入产品数据
        SmartModData smartModData = new SmartModData();
        smartModData.setType("mtr");
        smartModData.setState("0");
        List<SmartModData> list = smartModDataService.selectSmartModDataList(smartModData);
        insertProductBySmartModeData(list);
        //添加产品状态
        smartModDataService.setProductState(list);
    }

    private void insertProductTestWaveform(){
        SmartModData smartModData = new SmartModData();
        smartModData.setType("gdf");
        smartModData.setState("0");
        Integer listSize=1;
        while (listSize>0){
            List<SmartModData> list = smartModDataService.selectSmartModDataListTop1000(smartModData);
            listSize=list.size();
            for(SmartModData item : list){
                String productCode="";
                String testName="";
                String data=item.getData();
                try{
                    JSONArray arr = JSONArray.parseArray(item.getModStr());
                    for(int i = 0; i < arr.size(); i++){
                        JSONObject obj = arr.getJSONObject(i);
                        if(obj.containsKey("Id")){
                            productCode=obj.getString("Id");
                        }
                        if(obj.containsKey("测试项目")){
                            testName=obj.getString("测试项目");
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                SmartProductTestWaveform smartProductTestWaveform=new SmartProductTestWaveform();
                smartProductTestWaveform.setData(data);
                smartProductTestWaveform.setCreateDate(new Date());
                smartProductTestWaveform.setNotes(testName);
                smartProductTestWaveform.setProductCode("20"+productCode);
                smartProductTestWaveformService.insertSmartProductTestWaveform(smartProductTestWaveform);
                item.setState("1");
                smartModDataService.updateSmartModData(item);
            }
        }
    }

    //添加检验记录
    private void insertProductTest(JSONObject modStr, JSONObject modListItem){
        SmartProductTest smartProductTest=new SmartProductTest();
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
        if(modListItem.containsKey("switch id"))
        {
            smartProductTest.setProductId(modListItem.getString("switch id"));
        }
        if(modListItem.containsKey("The average current"))
        {
            smartProductTest.setCurrent(modListItem.getString("The average current"));
        }
        if(modListItem.containsKey("The average voltage"))
        {
            smartProductTest.setVoltage(modListItem.getString("The average voltage"));
        }
        if(modListItem.containsKey("Result"))
        {
            smartProductTest.setTestResult(modListItem.getString("Result"));
        }
        if(modListItem.containsKey("Result"))
        {
            try {
                smartProductTest.setCreateDate(formatter.parse(modListItem.getString("time")));  //设置时间
            } catch (ParseException e) {e.printStackTrace();}
        }
        if(modStr.containsKey("测试项目"))
        {
            smartProductTest.setState(modStr.getString("测试项目"));
        }
        if(modStr.containsKey("操作员"))
        {
            smartProductTest.setUserId(modStr.getString("操作员"));
        }
        if(modStr.containsKey("设备编号"))
        {
            smartProductTest.setDeviceId(modStr.getString("设备编号"));
        }

        smartProductTestService.insertSmartProductTest(smartProductTest);

    }

    private void insertProductBySmartModeData(List<SmartModData> list){
        Map<String,JSONObject> productCodes=new HashMap<>();
        for(SmartModData item : list){
            String modList = item.getModList();
            try{
                JSONArray arr = JSONArray.parseArray(modList);
                JSONObject modStr=JSONObject.parseObject(item.getModStr());
                for(int i = 0; i < arr.size(); i++){
                    JSONObject obj = arr.getJSONObject(i);
                    String switchId = obj.getString("switch id");
                    productCodes.put(switchId, obj);
                    insertProductTest(modStr,obj);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        for(String code : productCodes.keySet()){
            if(!"".equals(code)){
                SmartProduct smartProduct=new SmartProduct();
                try{
                    JSONObject obj = productCodes.get(code);
                    smartProduct.setCode(code);
                    smartProduct.setModel(String.valueOf(findProduct(code)));
                    Date date= null;
                    if(StringUtils.isNotEmpty(obj.getString("time")))
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(obj.getString("time").replace('_', ' '));
                    smartProduct.setCreateDate(date);
                    smartProduct.setFaultState("1");
                    String tastState = obj.getString("Result");
                    if(StringUtils.isNotEmpty(tastState)){
                        if(tastState.contains("不合格")){
                            tastState = "3";
                        }else if(tastState.contains("合格")){
                            tastState = "2";
                        }else if(tastState.contains("生产中")){
                            tastState = "1";
                        }
                    }
                    smartProduct.setTastState(tastState);
                    if(smartProductService.selectSmartProductList(smartProduct).size()<1)
                        smartProductService.insertSmartProduct(smartProduct);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /*private void insertProduct(List<SmartProcessData> list){
        Map<String,Date> productCodes=new HashMap<>();
        *//*for(SmartProcessData item : list){
            getProductId(item,productCodes);
            item.setState(1l);
            smartProcessDataMapper.updateSmartProcessData(item);
        }*//*
        for(String code : productCodes.keySet()){
            if(!"".equals(code)){
                SmartProduct smartProduct=new SmartProduct();
                smartProduct.setCode(code);
                smartProduct.setModel(String.valueOf(findProduct(code)));
                smartProduct.setCreateDate(productCodes.get(code));
                if(smartProductService.selectSmartProductList(smartProduct).size()<1)
                    smartProductService.insertSmartProduct(smartProduct);
            }
        }
    }*/

    /**
     * 查询产品型号
     */
    private Long findProduct(String productcode){
        Long productModelId=0l;
        String test="0000";
        if(productcode.length()>4){
           test=productcode.substring(0,4);
           SmartPlanTask smartPlanTask=new SmartPlanTask();
           smartPlanTask.setCode(test);
           List<SmartPlanTask> smartPlanTasks=smartPlanTaskService.selectSmartPlanTaskList(smartPlanTask);
           if(smartPlanTasks.size()<1){
               //返回创建的默认产品型号ID
               productModelId=creatDefult();
           }
           else {
               productModelId=smartPlanTasks.get(0).getProductId();
           }
        }else
        {
            //返回创建的默认产品型号ID
            productModelId=creatDefult();
        }
        return productModelId;
    }
    //创建默认产品型号
    private Long creatDefult(){
        Long productModelId;
        SmartProductModel product=new SmartProductModel();
        product.setPnId("00000000");
        List<SmartProductModel> products= smartProductModelService.selectSmartProductModelList(product);
        if(products.size()<1){
            product.setModel("默认产品");
            smartProductModelService.insertSmartProductModel(product);
            productModelId=product.getId();
        }
        else {
            //获取产品ID
            productModelId=products.get(0).getId();
        }


        SmartPlanTask smartPlanTask=new SmartPlanTask();
        smartPlanTask.setCode("00000000");
        List<SmartPlanTask> planTasks=smartPlanTaskService.selectSmartPlanTaskList(smartPlanTask);
        if(planTasks.size()<1){
            smartPlanTask.setName("默认计划");
            smartPlanTask.setProductId(productModelId);
            smartPlanTask.setPlanNum(1l);
            smartPlanTask.setNum(0l);
            smartPlanTaskService.insertSmartPlanTask(smartPlanTask);
        }
        return productModelId;
    }
    /**
     * 此方法用于找出当中的产品编码
     * @param smartProcessData
     * @return
     */
    private String getProductId(SmartProcessData smartProcessData,Map<String,Date> productCodes)
    {
        Date date=new Date();
        if(smartProcessData.getParamValue1()!=null&&smartProcessData.getParamValue2()!=null){
            String data=smartProcessData.getParamValue1()+" "+smartProcessData.getParamValue2();
            try {
                date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(data);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(smartProcessData.getParamValue1()!=null){
            if(smartProcessData.getParamValue1().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue1().split("=")[1],date);
                return smartProcessData.getParamValue1().split("=")[1];
            }

        }
        if(smartProcessData.getParamValue2()!=null){
            if(smartProcessData.getParamValue2().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue2().split("=")[1],date);
                return smartProcessData.getParamValue2().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue3()!=null){
            if(smartProcessData.getParamValue3().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue3().split("=")[1],date);
                return smartProcessData.getParamValue3().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue4()!=null){
            if(smartProcessData.getParamValue4().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue4().split("=")[1],date);
                return smartProcessData.getParamValue4().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue5()!=null){
            if(smartProcessData.getParamValue5().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue5().split("=")[1],date);
                return smartProcessData.getParamValue5().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue6()!=null){
            if(smartProcessData.getParamValue6().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue6().split("=")[1],date);
                return smartProcessData.getParamValue6().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue7()!=null){
            if(smartProcessData.getParamValue7().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue7().split("=")[1],date);
                return smartProcessData.getParamValue7().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue8()!=null){
            if(smartProcessData.getParamValue8().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue8().split("=")[1],date);
                return smartProcessData.getParamValue8().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue9()!=null){
            if(smartProcessData.getParamValue9().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue9().split("=")[1],date);
                return smartProcessData.getParamValue9().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue10()!=null){
            if(smartProcessData.getParamValue10().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue10().split("=")[1],date);
                return smartProcessData.getParamValue10().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue11()!=null){
            if(smartProcessData.getParamValue11().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue11().split("=")[1],date);
                return smartProcessData.getParamValue11().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue12()!=null){
            if(smartProcessData.getParamValue12().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue12().split("=")[1],date);
                return smartProcessData.getParamValue12().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue13()!=null){
            if(smartProcessData.getParamValue13().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue13().split("=")[1],date);
                return smartProcessData.getParamValue13().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue14()!=null){
            if(smartProcessData.getParamValue14().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue14().split("=")[1],date);
                return smartProcessData.getParamValue14().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue15()!=null){
            if(smartProcessData.getParamValue15().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue15().split("=")[1],date);
                return smartProcessData.getParamValue15().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue16()!=null){
            if(smartProcessData.getParamValue16().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue16().split("=")[1],date);
                return smartProcessData.getParamValue16().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue17()!=null){
            if(smartProcessData.getParamValue17().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue17().split("=")[1],date);
                return smartProcessData.getParamValue17().split("=")[1];
            }
        }
        if(smartProcessData.getParamValue18()!=null){
            if(smartProcessData.getParamValue18().contains("Id="))
            {
                productCodes.put(smartProcessData.getParamValue18().split("=")[1],date);
                return smartProcessData.getParamValue18().split("=")[1];
            }
        }
        return "";
    }

    /**
     * 查询工序数据列表
     * 
     * @param smartProcessData 工序数据
     * @return 工序数据
     */
    @Override
    public List<SmartProcessData> selectSmartProcessDataList(SmartProcessData smartProcessData)
    {
        // insertString("ss");
        return smartProcessDataMapper.selectSmartProcessDataList(smartProcessData);
    }

    /**
     * 新增工序数据
     * 
     * @param smartProcessData 工序数据
     * @return 结果
     */
    @Override
    public int insertSmartProcessData(SmartProcessData smartProcessData)
    {
        smartProcessData.setCreateTime(DateUtils.getNowDate());
        return smartProcessDataMapper.insertSmartProcessData(smartProcessData);
    }

    /**
     * 修改工序数据
     * 
     * @param smartProcessData 工序数据
     * @return 结果
     */
    @Override
    public int updateSmartProcessData(SmartProcessData smartProcessData)
    {
        return smartProcessDataMapper.updateSmartProcessData(smartProcessData);
    }

    /**
     * 批量删除工序数据
     * 
     * @param ids 需要删除的工序数据主键
     * @return 结果
     */
    @Override
    public int deleteSmartProcessDataByIds(Long[] ids)
    {
        return smartProcessDataMapper.deleteSmartProcessDataByIds(ids);
    }

    /**
     * 删除工序数据信息
     * 
     * @param id 工序数据主键
     * @return 结果
     */
    @Override
    public int deleteSmartProcessDataById(Long id)
    {
        return smartProcessDataMapper.deleteSmartProcessDataById(id);
    }

}
